/**
 * MCP工具管理 API
 */

import axios from 'axios'

// 基础配置 - 统一使用vite代理配置
const API_BASE_URL = '/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    console.log('MCP API Request:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    console.error('MCP Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    console.log('MCP API Response:', response.status, response.config.url)
    return response.data
  },
  (error) => {
    console.error('MCP Response Error:', error.response?.status, error.config?.url)
    return Promise.reject(error)
  }
)

// 工具函数：过滤空值参数
const filterEmptyParams = (params?: Record<string, any>) => {
  if (!params) return undefined
  return Object.fromEntries(
    Object.entries(params).filter(([_, value]) => value !== null && value !== undefined && value !== '')
  )
}

// ================== 类型定义 ==================

export interface MCPTool {
  id: string
  mcp_name: string
  description?: string
  status: number
  access_type: number
  doc_url?: string
  json_schema?: Record<string, any>
  created_at: string
  updated_at: string
  status_display?: string
  access_type_display?: string
  tools_count?: number
  enabled_tools_count?: number
  statusLoading?: boolean
}

export interface MCPToolCreate {
  id?: string
  mcp_name: string
  description?: string
  status?: number
  access_type: number
  doc_url?: string
  json_schema?: Record<string, any>
}

export interface MCPToolUpdate {
  mcp_name?: string
  description?: string
  status?: number
  access_type?: number
  doc_url?: string
  json_schema?: Record<string, any>
}

export interface MCPToolSearchParams {
  page?: number
  page_size?: number
  mcp_name?: string
  status?: number
  access_type?: number
}

export interface MCPToolListResponse {
  total: number
  items: MCPTool[]
}

export interface DetailTool {
  id: number
  parent_id: string
  tool_name: string
  description?: string
  is_enabled: boolean
  human_interactive_flag: number
  parameters: any[]
  created_at: string
  updated_at: string
  statusLoading?: boolean
  interactiveLoading?: boolean
}

export interface DetailToolUpdate {
  tool_name?: string
  description?: string
  is_enabled?: boolean
  parameters?: any[]
}

export interface DetailToolListResponse {
  total: number
  items: DetailTool[]
}

export interface MCPStats {
  total_count: number
  testing_count: number
  online_count: number
  discontinued_count: number
  api_count: number
  local_tool_count: number
  total_tools_count: number
  enabled_tools_count: number
  connected_servers_count: number
  connected_servers: string[]
}

export interface StatusOption {
  value: number
  label: string
}

export interface AccessTypeOption {
  value: number
  label: string
}

// ================== MCP工具集管理 ==================

/**
 * 获取MCP工具列表
 */
export const getMCPTools = (params?: MCPToolSearchParams): Promise<MCPToolListResponse> => 
  apiClient.get('/mcp/list', { params: filterEmptyParams(params) })

/**
 * 创建MCP工具
 */
export const createMCPTool = (data: MCPToolCreate): Promise<MCPTool> => 
  apiClient.post('/mcp/create', data)

/**
 * 更新MCP工具
 */
export const updateMCPTool = (id: string, data: MCPToolUpdate): Promise<MCPTool> => 
  apiClient.put(`/mcp/${id}`, data)

/**
 * 删除MCP工具
 */
export const deleteMCPTool = (id: string): Promise<{ message: string }> => 
  apiClient.delete(`/mcp/${id}`)

/**
 * 获取MCP工具详情
 */
export const getMCPTool = (id: string): Promise<MCPTool> => 
  apiClient.get(`/mcp/${id}`)

/**
 * 更新MCP工具状态
 */
export const updateMCPToolStatus = (id: string, status: number): Promise<MCPTool> => 
  apiClient.put(`/mcp/${id}/status`, { status })

// ================== MCP工具详情管理 ==================

/**
 * 获取MCP工具下的详情工具列表
 */
export const getMCPDetailTools = (mcpId: string): Promise<DetailToolListResponse> => 
  apiClient.get(`/mcp/${mcpId}/tools`)

/**
 * 更新MCP工具详情
 */
export const updateMCPDetailTool = (mcpId: string, toolId: number, data: DetailToolUpdate): Promise<DetailTool> => 
  apiClient.put(`/mcp/${mcpId}/tools/${toolId}`, data)

/**
 * 删除MCP工具详情
 */
export const deleteMCPDetailTool = (mcpId: string, toolId: number): Promise<{ message: string }> => 
  apiClient.delete(`/mcp/${mcpId}/tools/${toolId}`)

/**
 * 更新MCP工具详情状态
 */
export const updateMCPDetailToolStatus = (mcpId: string, toolId: number, isEnabled: boolean): Promise<DetailTool> => 
  apiClient.put(`/mcp/${mcpId}/tools/${toolId}/status`, { is_enabled: isEnabled })

/**
 * 更新MCP工具详情人工交互标识
 */
export const updateMCPDetailToolInteractive = (mcpId: string, toolId: number, flag: number): Promise<DetailTool> => 
  apiClient.put(`/mcp/${mcpId}/tools/${toolId}/interactive`, { human_interactive_flag: flag })

// ================== 辅助接口 ==================

/**
 * 获取状态选项
 */
export const getStatusOptions = (): Promise<StatusOption[]> => 
  apiClient.get('/mcp/options/status')

/**
 * 获取接入类型选项
 */
export const getAccessTypeOptions = (): Promise<AccessTypeOption[]> => 
  apiClient.get('/mcp/options/access-type')

/**
 * 获取已连接的服务器列表
 */
export const getConnectedServers = (): Promise<{ connected_servers: string[], count: number }> => 
  apiClient.get('/mcp/connected-servers')

/**
 * 获取MCP统计信息
 */
export const getMCPStats = (): Promise<MCPStats> => 
  apiClient.get('/mcp/stats')

// ================== 导出所有API ==================

export const mcpApi = {
  // MCP工具集管理
  getMCPTools,
  createMCPTool,
  updateMCPTool,
  deleteMCPTool,
  getMCPTool,
  updateMCPToolStatus,
  
  // MCP工具详情管理
  getMCPDetailTools,
  updateMCPDetailTool,
  deleteMCPDetailTool,
  updateMCPDetailToolStatus,
  updateMCPDetailToolInteractive,
  
  // 辅助接口
  getStatusOptions,
  getAccessTypeOptions,
  getMCPStats,
  getConnectedServers
} 